package com.fiberhome.opticalbox.net;

import android.app.Activity;

import com.fiberhome.opticalbox.net.TcpMander.OnTcpCommunicateListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.bean.ResponseBean;

/**
 * tcp helper class
 * 
 * @author wangpeng
 * @date 2014-12-24
 */
public class NetManager {

	private TcpMander tcpMander;

	public NetManager(final Activity activity, final TcpListener tcpListener, final TcpErrorListener tcpErrorListener) {
		tcpMander = new TcpMander(new OnTcpCommunicateListener() {

			@Override
			public void onError(Exception exception, String sendStr) {
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (tcpListener != null) {
							tcpErrorListener.onError("onError");
						}
					}
				});
			}

			@Override
			public void onComplete(final ResponseBean response, final Object... args) {
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {

						Parameter param = response.getParameter();
						String status = param.getStatus();
						if (NetConstant.FAIL.equals(status)) {
							if (tcpListener != null) {
								tcpErrorListener.onError(param.getCmdType());
							}
						} else {
							if (tcpListener != null) {
								tcpListener.onReceive(param.getCmdType(), param);
							}
						}
					}
				});
			}
		});
	}

	public void sendTcp(byte[] input) {
		if (tcpMander != null) {
			tcpMander.sendTcp(input);
		}
	}

	public void stop() {
		if (tcpMander != null) {
			tcpMander.shutdownAndAwaitTermination();
		}
	}

	public void setTimeout(int timeout) {
		if (tcpMander != null) {
			tcpMander.setTimeout(timeout);
		}
	}

	public interface TcpListener {
		public void onReceive(String cmdType, Parameter param);
	}

	public interface TcpErrorListener {
		public void onError(String cmdType);
	}
}
